# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 聚合管道操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 21:36
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']

pipeline = [
    {
        "$addFields": {
            "is_adult": {
                "$cond": [{"$gte": ["$age", 18]}, True, False]  # 年龄 >= 18 则为 True
            }
        }
    },
    {"$project": {"name": 1, "age": 1, "is_adult": 1, "_id": 0}},  # 只显示这几个字段
    {"$skip": 1},
    {"$limit": 5}
]

result = list(db.users.aggregate(pipeline))
for user in result:
    print(user)


"""
{'name': 'User_2', 'age': 50, 'is_adult': True}
{'name': 'User_3', 'age': 42, 'is_adult': True}
{'name': 'User_4', 'age': 30, 'is_adult': True}
{'name': 'User_5', 'age': 47, 'is_adult': True}
{'name': 'User_6', 'age': 16, 'is_adult': False}
"""
